<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<base href="/">
	<meta charset="utf-8">
	<link rel="stylesheet" href="fonts/iconfont.css">
	<link rel="stylesheet" href="layui/css/layui.css">
	<link rel="stylesheet" href="list/list.css">
	<script src="layui/layui.all.js"></script>
	<title>商品页面</title>
</head>
<body>
<div class="top-bar tonglan">
	<div class="top-nav-wrapper w">
		<div class="top-nav-left">
		</div>
		<div class="top-nav-right">
			<ul>
				<li><a href="page/index">首页</a></li><span></span>
				<li><a href="page/orderConfirm">我的订单</a></li> <span></span>
				<li><a href="page/cart">购物车</a></li> <span></span>
				<li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
				<li>
					<a href="#" id="logoutLink">退出登录</a>
				</li>
			</ul>
		</div>
	</div>
</div>
<div class="tonglan nav-bar">
	<div class="w">
		<div class="nav-logo">
			<img src="images/LOGO_2.png" alt="">
		</div>
		<div class="search">
			<form action="" name="search">
				<input type="text" name="words" placeholder="请输入搜索关键字">
				<button type="submit">搜索</button>
			</form>
		</div>
		<div class="menu-wrapper">
			<div class="menu-wrapper-left">
				<ul _id="categorylist">
					<li style="border-bottom: none;">
						<a href="page/index">首页</a>
					</li>
				</ul>
			</div>
			<div class="menu-wrapper-right">
			</div>
		</div>
	</div>
</div>


<div class="w sort-wrapper">
            <span data-key="price" class="sort-item active asc">
                价格
                <i class="iconfont icon-sort-down"></i>
                <i class="iconfont icon-sort-up"></i>
            </span>
	<span data-key="sales" class="sort-item asc">
                销量
                <i class="iconfont icon-sort-down"></i>
                <i class="iconfont icon-sort-up"></i>
            </span>
	<div class="search">
		<form action="" name="search">


		</form>
	</div>
</div>


<div class="w menu-price">

</div>
<div id="pagebox">

</div>


<button class="ricker" id="backToTopBtn">顶部</button>
<!--        <script src="list/list.js"></script>-->

<script type="text/html" _id="categoryitem">
	<li>
		<a href="page/list"></a>
		<div>
			<ul class="menu-main w">

			</ul>
		</div>
	</li>
</script>
<script type="text/html" id="categorychild">
	<li>
		<a href="">
			<img src="" alt="">
			<span></span>
		</a>
	</li>
</script>

<script>

	const $ = layui.$;
	const laypage=layui.laypage;


	// 从 URL 中获取分类信息
	function getCategoryFromUrl() {
		const params = new URLSearchParams(window.location.search);
		return params.get('category');
	}

	//父级分类下拉二级分类事件

	$.ajax({
		url: 'category/list',
		data: {id: -1},
		success: function (result) {
			let data = result.data;
			console.log(data);

			// 筛选出 pid 为 -1 的父级分类
			const parentCategories = data.filter(item => item.pid === -1);

			parentCategories.forEach((parent) => {
				let item = $('script[_id="categoryitem"]').text();
				let $item = $(item);
				$item.children("a").text(parent.categoryname);
				$item.children("a").attr("href", `page/list?category=${parent.categoryname}`);
				let $ul = $item.find("ul");

				// 发起请求获取子分类
				$.ajax({
					url: "category/getChildren",
					data: {id: parent.categoryid},
					success: function (res) {
						// 内层循环使用不同的变量名 j
						for (let j = 0; j < res.length; j++) {
							let childtext = $("#categorychild").text();
							let $child = $(childtext);
							$child.find("span").text(res[j].categoryname);
							$child.find("img").attr("src", res[j].imgurl);
							$child.find("a").attr("href", `page/list?category=${res[j].categoryname}`);
							$ul.append($child);
						}
					},
					error: function (error) {
						console.error(`获取 ${parent.categoryname} 的子分类失败:`, error);
					}
				});

				$('ul[_id="categorylist"]').append($item);
			});
		},
		error: function (error) {
			console.error('获取分类列表失败:', error);
		}
	});


	//回到顶部按钮事件
	const backToTopBtn = document.getElementById('backToTopBtn');
	backToTopBtn.addEventListener('click', function () {
		window.scrollTo({
			top: 0,
			behavior: 'smooth'
		});
	});





	let currentPage = 1; // 当前页码
	const pageSize = 9; // 每页显示数量
	let searchKeywords = ''; // 新增：存储搜索关键字
	let allProducts = []; // 存储所有商品数据

	layui.use(['jquery'], function () {
		const $ = layui.$;

		let listShow = [];
		let ob = null;
		let sortDir = "asc";
		let sortKey = "price";
		const menu = document.querySelector(".menu-price");

		// 获取所有商品数据
		function getAllProducts() {
			const category = getCategoryFromUrl();
			$.ajax({
				url: '/product/list', // 对应后端接口
				type: 'GET',
				dataType: 'json',
				data: {
					text: searchKeywords, // 添加搜索关键字参数
					category: category // 添加分类参数
				},
				success: function (res) {
					allProducts = res.data.map(item => ({
						productid: item.productid,
						name: item.productname,    // 映射字段
						price: item.price,
						descriptin: item.description,
						img: item.imgurl,
						sales: item.sales
					}));
					sortAndUpdateList();
					// 更新分页组件
					laypage.render({
						elem: 'pagebox',
						count: allProducts.length, // 总数据量
						limit: pageSize, // 每页显示数量
						curr: currentPage, // 当前页码
						layout: ['prev', 'page', 'next', 'count'],
						jump: function (obj, first) {
							if (!first) {
								currentPage = obj.curr;
								sortAndUpdateList();
							}
						}
					});
				},
				error: function (err) {
					console.error('数据加载失败:', err);
					alert('商品加载失败，请刷新重试');
				}
			});
		}

		// 排序并更新列表
		function sortAndUpdateList() {
			listShow = [...allProducts].sort((a, b) =>
					sortDir === "asc" ? a[sortKey] - b[sortKey] : b[sortKey] - a[sortKey]
			);
			const startIndex = (currentPage - 1) * pageSize;
			const endIndex = startIndex + pageSize;
			const currentPageProducts = listShow.slice(startIndex, endIndex);
			updateList(currentPageProducts);
		}

		// 初始化页面时加载数据
		$(document).ready(function () {
			getAllProducts();
		});

		function updateList(products) {
			var htmlStr = "";
			if (products.length === 0) {
				htmlStr = '<p style="text-align: center; color: #999; font-size: 24px;">暂时没有该商品</p>';
			} else {
				products.forEach(function (item) {
					htmlStr += `
                <div>
                    <a>
                        <img data-src="${item.img}" alt="">
                    </a>
                    <h5>${item.name}</h5>
                    <p>${item.descriptin}</p>
                    <span>${item.price}.00元</span>
                    <span>销量: ${item.sales}</span>
                    <button class="layui-btn layui-btn-normal buy-btn" data-productid="${item.productid}">立即购买</button>
                </div>
            `;
				});
			}

			menu.innerHTML = htmlStr;

			if (products.length > 0) {
				bindBuyButtonEvents();
				// 重新初始化懒加载
				initLazyLoad();
			}
		}

		// 绑定立刻购买跳转事件
		function bindBuyButtonEvents() {
			document.querySelectorAll(".buy-btn").forEach(btn => {
				btn.addEventListener("click", function () {
					const productid = this.dataset.productid;
					console.log(productid);
					window.location.href = `page/detail?productid=${productid}`;
				});
			});
		}

		// 初始化图片懒加载
		function initLazyLoad() {
			if (ob) ob.disconnect();
			ob = new IntersectionObserver(function (entries) {
				entries.forEach(function (entry) {
					if (entry.isIntersecting) {
						entry.target.src = entry.target.dataset.src;
						ob.unobserve(entry.target);
					}
				});
			}, { threshold: 0.1 });

			document.querySelectorAll(".menu-price img").forEach(img => {
				ob.observe(img);
			});
		}

		// 搜索逻辑
		document.forms["search"].onsubmit = function (e) {
			e.preventDefault();
			searchKeywords = this.words.value.trim().toLowerCase(); // 更新搜索关键字
			currentPage = 1; // 重置为第一页
			getAllProducts(); // 重新加载数据
		};


		// 排序逻辑
		document.querySelectorAll("span.sort-item").forEach(item => {
			item.onclick = function () {
				document.querySelectorAll("span.sort-item").forEach(sortItem => {
					sortItem.classList.remove("active");
				});
				this.classList.add("active");
				sortKey = this.dataset.key;
				if (sortKey === "price" || sortKey === "sales") {
					// 切换排序方向
					sortDir = sortDir === "asc" ? "desc" : "asc";
					// 更新排序图标
					if (sortDir === "asc") {
						this.classList.add("asc");
						this.classList.remove("desc");
					} else {
						this.classList.add("desc");
						this.classList.remove("asc");
					}
				}
				sortAndUpdateList();
			};
		});
	});
	// 退出登录逻辑
	const logoutLink = document.getElementById('logoutLink');
	logoutLink.addEventListener('click', function (e) {
		e.preventDefault(); // 阻止默认的链接跳转行为
		// 弹出确认提示框
		if (confirm('确定要退出登录吗？')) {
			$.ajax({
				url: 'logout', // 后端退出登录的接口地址
				method: 'GET',
				success: function (response) {
					if (response.code === 200) {
						// 退出登录成功，给出提示并跳转到登录页面
						alert(response.msg);
						window.location.href = 'page/login';
					} else {
						// 退出登录失败，给出提示
						alert(response.msg);
					}
				},
				error: function (error) {
					console.error('退出登录失败:', error);
					alert('退出登录时发生错误，请稍后再试。');
				}
			});
		}
	});
</script>
</body>
</html>